package be.kuleuven.mume;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.ariadne_eu.hcifetcher.util.DateManager;
import org.joda.time.DateTime;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Text;

public class JSONHelper {

	public static final String SUCCES = "{\"result\": \"Succes!\"}";
	public static final String NOTIMPLEMENTED = "{\"error\":\"needs to be implemented\"}";
	public static final String ERROR = "{\"error\":\"Error occured. See log for more details\"}";
	
	/**
	 * Generic Function to get a query of some type as JSON.
	 * 
	 * @param query
	 * @param type
	 * @param size
	 * @param offset
	 * @return
	 * @throws JSONException
	 */
	public static JSONObject getQueryAsJSON(Query query, String type, int size, int offset) throws JSONException{
		JSONArray results = new JSONArray();
		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
		List<Entity> result = datastore.prepare(query).asList(FetchOptions.Builder.withLimit(size).offset(offset*size));
		for (Entity entity : result) {
			JSONObject ent = new JSONObject();
			Map<String, Object> props = entity.getProperties();
			
			ent.put("key", KeyFactory.keyToString(entity.getKey()));
			ent.put("entitytype", type);
			
			for (String key : props.keySet()) {
				Object object = props.get(key);			
				String value = "";
				if(object !=null)value = object.toString();
				if(object instanceof Text) value = ((Text)object).getValue();
				if(object instanceof Date) value = DateManager.fmt1.print(new DateTime((Date)object));
				ent.put(key, value);
			}
			results.put(ent);
		}
		
		JSONObject json = new JSONObject();
		
		json.put("total_results", results.length());
		json.put("result", results);
		
		return json;
	}
	
	public static JSONObject convertToJSONResult(List<?> list) throws JSONException{
		JSONArray array = new JSONArray();
		
		for (Object o : list) {
			array.put((new JSONObject(o)));
		}
		
		return convertToJSONResult(array);
	}
	
	public static JSONObject convertToJSONResult(JSONObject o) throws JSONException{
		JSONObject result = new JSONObject();
		result.put("result", o);
		return result;
	}
	
	public static JSONObject convertToJSONResult(JSONArray o) throws JSONException{
		JSONObject result = new JSONObject();
		result.put("result", o);
		return result;
	}
}
